var qs=require('qs');
var crypto=require('crypto');
var url=require('url');
var TOKEN="ningtowen";
var fs=require('fs');
var weChart=require(process.cwd()+'/server/util/weChartMessage.js');
var dataPath=process.cwd()+'/data/wechart.json';

module.exports.handleGet=function(request,response){
	var query=url.parse(request.url).query;
	var params=qs.parse(query);
	if(!weChart.checkSignature(params,TOKEN)){
		response.end('signature fail');
	}else{
		response.end(params.echostr);
	}
}

module.exports.handleData=function(request,response){
		var query=url.parse(request.url).query;
		var params=qs.parse(query);
		if(!weChart.checkSignature(params,TOKEN)){
			response.end('signature fail');
		}else{
			var _da;
		    request.on("data",function(data){
		        _da = data.toString("utf-8");

		    });
		    request.on("end",function(){
		        var MsgType = weChart.getXMLNodeValue('MsgType',_da);
		        var xml="";
		        switch(MsgType.replace('<![CDATA[','').replace(']]>','')){
		        	case 'text':
		        		xml=weChart.weChartMessage(_da);		        		
		        		response.send(xml);
		        		break;
		        	case 'image':
		        		xml=weChart.weChartImage(_da);
		        		response.send(xml);
		        		break;
		        	case 'voice':
		        		xml=weChart.weChartVoice(_da);
		        		response.send(xml);
		        		break;
		        	case 'shortvideo':
		        		xml=weChart.weChartShortvideo(_da);
		        		response.send(xml);
		        		break;
		        	default :
		        		xml="success";
		        		response.send(xml);
		        		break;
		        }
		    });
		}		
}

/*module.exports.getData=function(request,response){
	fs.readFile(dataPath,'utf-8',function(err,data){
		console.log(data);
		response.send(data);
	});
}

module.exports.writeData=function(request,response){
	console.log('writeData');
	console.log(request.body);
	var postdata=JSON.stringify(request.body);			
	fs.readFile(dataPath,'utf-8',function(err,data){
		var tempdata=data+"/:1/"+postdata+"/:2/"+request.url+"\n";
		console.log(tempdata);
		fs.writeFile(dataPath,tempdata,'utf-8',function(err){					
		response.end("success");
		});
	});
}*/